﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Linq;

namespace Qy.Web.Authorize;

/// <summary>
/// JWT授权校验访问  借鉴 ZRADMIN https://gitee.com/izory/ZrAdminNetCore
/// 如果跳过授权登录在Action 或controller加上 AllowAnonymousAttribute
/// </summary>
[AttributeUsage(AttributeTargets.All)]
public class VerifyAttribute : Attribute, IAuthorizationFilter
{
    /// <summary>
    /// 判断token是否正确
    /// </summary>
    /// <param name="context"></param>
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        var noNeedCheck = false;
        if (context.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor)
        {
            noNeedCheck = controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true)
              .Any(a => a.GetType().Equals(typeof(AllowAnonymousAttribute)));
        }
        if (noNeedCheck) return;

        if (JwtHelper.GetLoginUser() == null)
        {
            string msg = $"请求访问[" + context.HttpContext.Request.Path + "]失败，有可能登录过期，需重新登录";
            JsonResult result = new(new { status = 401, msg })
            {
                ContentType = "application/json",
            };
            context.Result = result;
        }
    }
}
